package de.unikoblenz.west.csxpoi;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * A collection of methods to encode strings.
 */
public class Encoder {

	/**
	 * Encodes a string for a URL.
	 * 
	 * @param string
	 *            the string to encode
	 * @return the encoded string
	 * @throws UnsupportedEncodingException
	 */
	public static String urlEncode(String string)
			throws UnsupportedEncodingException {
		// TODO: proper encoding
		// (standard causes problems with umlauts and URL rewriter)
		return URLEncoder.encode(string, "ISO-8859-1").replaceAll("%2F", "/");
	}

	/**
	 * Generates the SHA-1 hash of a string.
	 * 
	 * @param string
	 *            the string to hash
	 * @return the hashed string
	 */
	public static String sha1Hash(String string) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			byte[] sha1hash = new byte[40];
			md.update(string.getBytes("iso-8859-1"), 0, string.length());
			sha1hash = md.digest();
			return convertToHex(sha1hash);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * Converts a byte array to a string.
	 * 
	 * @param data
	 *            the byte array to convert
	 * @return the converted string
	 */
	private static String convertToHex(byte[] data) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < data.length; i++) {
			int halfbyte = (data[i] >>> 4) & 0x0F;
			int two_halfs = 0;
			do {
				if ((0 <= halfbyte) && (halfbyte <= 9)) {
					buf.append((char) ('0' + halfbyte));
				} else {
					buf.append((char) ('a' + (halfbyte - 10)));
				}
				halfbyte = data[i] & 0x0F;
			} while (two_halfs++ < 1);
		}
		return buf.toString();
	}
}
